﻿# -*- coding:utf-8 -*-
import os
import sys
import time
import pygame

'''配置类'''
class Config():
    # 根目录
    rootdir = os.path.split(os.path.abspath(__file__))[0]
    # FPS
    FPS = 30
    # 屏幕大小
    SCREENSIZE = (1024, 700)
    # 标题
    TITLE = '简单HIIT定时器'

    #在这里修改你想要的锻炼和休息的秒数，坚持锻炼吧
    WORKOUT_SECONDS_SET = 40
    REST_SECONDS_SET = 20
    ROUNDS_SET = 30


    '''在屏幕指定位置显示文字'''
def showText(screen, font, text, color, position):
    text_render = font.render(text, True, color)
    rect = text_render.get_rect()
    rect.left, rect.top = position
    screen.blit(text_render, rect)
    return rect.right


'''按钮'''
def Button(screen, position, text, font, buttoncolor=(120, 120, 120), linecolor=(20, 20, 20), textcolor=(255, 255, 255), bwidth=200, bheight=50):
    left, top = position
    pygame.draw.line(screen, linecolor, (left, top), (left+bwidth, top), 5)
    pygame.draw.line(screen, linecolor, (left, top-2), (left, top+bheight), 5)
    pygame.draw.line(screen, linecolor, (left, top+bheight), (left+bwidth, top+bheight), 5)
    pygame.draw.line(screen, linecolor, (left+bwidth, top+bheight), (left+bwidth, top), 5)
    pygame.draw.rect(screen, buttoncolor, (left, top, bwidth, bheight))
    text_render = font.render(text, 1, textcolor)
    rect = text_render.get_rect()
    rect.centerx, rect.centery = left + bwidth / 2, top + bheight / 2
    return screen.blit(text_render, rect)

'''退出程序'''
def QuitGame(use_pygame=True):
    if use_pygame: pygame.quit()
    sys.exit()



# 设置bgm播放列表，可以替换成你喜欢的音乐
bgm_list = ["bgm1.mp3", "bgm2.mp3"]
current_bgm = 0
 
# 加载并播放下一首bgm
def play_next_bgm():
    global current_bgm
    current_bgm = (current_bgm + 1) % len(bgm_list)
    pygame.mixer.music.load(bgm_list[current_bgm])
    pygame.mixer.music.play()

class HIIT_timer():
    
    def __init__(self):
        self.cfg = Config
        
    '''运行游戏'''
    def run(self):
        # 初始化
        BLACK_COLOR = (0,0,0)
        WHITE_CLOLR = (255,255,255)
        GREEN_COLOR = (0,255,0)
        RED_COLOR = (255,0,0)
        BLUE_COLOR = (0,0,255)

        bg_color = GREEN_COLOR
        text_color = BLACK_COLOR

        cfg = self.cfg

        pygame.init()
        screen = pygame.display.set_mode(cfg.SCREENSIZE)
        pygame.display.set_caption(cfg.TITLE)
        #中文字体不是所有系统都有
        font = pygame.font.SysFont('Consolas', 70)
        #font = pygame.font.SysFont('FreeMono', 80)
        #font.set_bold(1)
        
        pygame.mixer.init()
        #加载和播放背景音乐
        #pygame.mixer.music.set_volume(0.5)
        pygame.mixer.music.load(bgm_list[current_bgm])
        pygame.mixer.music.play()

        #加载提示音，自己手机录的，见笑啦！
        #录制出来时m4a格式，在https://app.xunjieshipin.com/m4a-to-mp3/ 在线转成的MP3，点赞！
        rest_sound = pygame.mixer.Sound('rest.mp3')
        #rest_sound.set_volume(1)
        workout_sound = pygame.mixer.Sound('workout.mp3')
        #workout_sound.set_volume(1)

        # 加载背景图片
        background_image = pygame.image.load('壶铃摇摆-1.jpeg').convert()

        workout_seconds = 0
        rest_seconds = 0
        rounds = 0
        start_time = time.time()
        playing_rest_flag = False
        playing_workout_flag = False

        clock = pygame.time.Clock()

        state = "working"
        pause_start_time = 0
        pause_duration = 0
        while True:
            #########################
            dt = clock.tick(cfg.FPS)
            #########################

            screen.fill(bg_color)
            # 将背景图片绘制到屏幕上
            screen.blit(background_image, (cfg.SCREENSIZE[0]-480, 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    QuitGame()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        if state == "working":
                            state = "pause"
                            pygame.mixer.music.pause()
                            #记录暂停开始的时刻，用于后续计算暂停持续时间
                            pause_start_time = time.time()
                        else:
                            state = "working"
                            pygame.mixer.music.unpause()
                            #计算暂停持续时间，更新start_time跳过这段暂停时间
                            pause_duration = time.time()-pause_start_time
                            start_time += pause_duration

            if state=="pause":
                continue

            if not pygame.mixer.music.get_busy():
                # 播放下一首bgm
                play_next_bgm()

            DurationSeconds = time.time() - start_time
            rounds = int(DurationSeconds / (cfg.WORKOUT_SECONDS_SET + cfg.REST_SECONDS_SET))

            #一直显示锻炼结束，直到用户结束程序
            if rounds >= cfg.ROUNDS_SET:
                pygame.mixer.music.stop()
                screen.fill(GREEN_COLOR)
                showText(screen, font, 'Done!!!', RED_COLOR, (int(cfg.SCREENSIZE[0] * 0 + 10), 10))
                # 将背景图片绘制到屏幕上
                screen.blit(background_image, (cfg.SCREENSIZE[0]-480, 0))
                pygame.display.update()
                continue    

            workout_seconds = DurationSeconds - rounds*(cfg.WORKOUT_SECONDS_SET + cfg.REST_SECONDS_SET)
            if workout_seconds>cfg.WORKOUT_SECONDS_SET:
                #本轮是休息时间
                playing_workout_flag=False
                rest_seconds = DurationSeconds - rounds*(cfg.WORKOUT_SECONDS_SET + cfg.REST_SECONDS_SET) - cfg.WORKOUT_SECONDS_SET
                if int(rest_seconds) == 0 and playing_rest_flag==False:
                    #播放开始休息提示音
                    playing_rest_flag = True
                    rest_sound.play()
                workout_seconds = 0
                text_color = WHITE_CLOLR
                bg_color = BLUE_COLOR
                showText(screen, font, 'rest: %d/%d' % (rest_seconds,cfg.REST_SECONDS_SET), text_color, (int(cfg.SCREENSIZE[0] * 0 + 20), 50))
            else:
                #在锻炼时间内
                playing_rest_flag=False
                if int(workout_seconds) == 0 and playing_workout_flag==False:
                    #播放开始锻炼提示音
                    playing_workout_flag=True
                    workout_sound.play()
                rest_seconds = cfg.REST_SECONDS_SET
                text_color = BLACK_COLOR
                bg_color = GREEN_COLOR
                showText(screen, font, 'work: %d/%d' % (workout_seconds, cfg.WORKOUT_SECONDS_SET), text_color, (int(cfg.SCREENSIZE[0] * 0 + 20), 50))

            showText(screen, font, 'round: %d/%d' % (rounds,cfg.ROUNDS_SET), text_color, (int(cfg.SCREENSIZE[0] * 0 + 10), 200))
            showText(screen, font, 'SPACE: PAUSE' , text_color, (int(cfg.SCREENSIZE[0] * 0 + 10), 350))
            showText(screen, font, 'You can DO it!' , text_color, (int(cfg.SCREENSIZE[0] * 0 + 10), 550))

            pygame.display.update()


if __name__ == '__main__':
    timer = HIIT_timer()
    timer.run()

